<template>
  <div class="server-list-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="showDialog()">
        <el-icon><Plus /></el-icon>添加服务器
      </el-button>
    </div>

    <!-- 服务器列表 -->
    <el-table v-loading="loading" :data="servers" style="width: 100%">
      <el-table-column prop="hostname" label="主机名" />
      <el-table-column prop="server_brand" label="品牌" />
      <el-table-column prop="server_model" label="型号" />
      <el-table-column prop="sn" label="序列号" />
      <el-table-column prop="location" label="位置">
        <template #default="{ row }"> {{ row.location }} U </template>
      </el-table-column>
      <el-table-column prop="height" label="高度">
        <template #default="{ row }"> {{ row.height }} U </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 服务器表单对话框 -->
    <ServerForm
      v-model:visible="dialogVisible"
      :server-data="currentServer"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ServerInfo } from '@/api/types'
import { assetService } from '@/api/assetService'
import { useRoomConfigStore } from '@/store/roomConfigStore'
import ServerForm from './ServerForm.vue'
import ServerDetail from './ServerDetail.vue'
import { Plus } from '@element-plus/icons-vue'

const dialogVisible = ref(false)
const currentServer = ref<ServerInfo | undefined>()

const roomConfigStore = useRoomConfigStore()
const { currentRoom } = storeToRefs(roomConfigStore)
const loading = ref(false)
const servers = ref<ServerInfo[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 显示对话框
const showDialog = (server?: ServerInfo) => {
  currentServer.value = server
  dialogVisible.value = true
}

// 处理添加
const handleAdd = () => {
  showDialog()
}

// 处理编辑
const handleEdit = (server: ServerInfo) => {
  showDialog(server)
}

// 对话框操作成功
const handleDialogSuccess = () => {
  loadServers()
}

// 加载服务器列表
const loadServers = async () => {
  if (!currentRoom.value) {
    ElMessage.warning('请先选择机房')
    return
  }
  loading.value = true
  try {
    const response = await assetService.getServersByRoom(currentRoom.value.room_id, {
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    servers.value = response.items
    total.value = response.total
  } catch (err) {
    console.error('获取服务器列表失败:', err)
    ElMessage.error('获取服务器列表失败')
  } finally {
    loading.value = false
  }
}

// 监听机房变化
watch(
  () => currentRoom.value?.room_id,
  (newRoomId) => {
    if (newRoomId) {
      currentPage.value = 1 // 重置页码
      loadServers()
    } else {
      servers.value = []
      total.value = 0
    }
  },
  { immediate: true },
)

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadServers()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadServers()
}

// 处理删除
const handleDelete = async (server: ServerInfo) => {
  try {
    await ElMessageBox.confirm('确定要删除该服务器吗？', '提示', {
      type: 'warning',
    })
    await assetService.deleteServer(server.id)
    ElMessage.success('删除成功')
    loadServers()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除服务器失败:', err)
      ElMessage.error('删除失败')
    }
  }
}
</script>

<style scoped lang="scss">
.server-list-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
